package xyz.ssf.cloud.common.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import xyz.ssf.cloud.common.core.storage.StorageFactory;
import xyz.ssf.cloud.common.core.storage.StorageStrategy;

import java.io.File;

/**
 * 存储配置类
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "storage")
public class StorageConfig {
    
    /**
     * 存储类型: local-本地存储, upyun-又拍云存储
     */
    private String type = "local";
    
    /**
     * 本地存储配置
     */
    private Local local = new Local();
    
    /**
     * 又拍云存储配置
     */
    private UpYun upyun = new UpYun();
    
    /**
     * 本地存储策略Bean
     */
    @Bean
    public StorageStrategy localStorageStrategy() {
        String storagePath = local.getStoragePath();
        String accessPath = local.getAccessPath();
        String domain = local.getDomain();
        
        // 处理存储路径，转换为绝对路径
        if (storagePath.startsWith("./")) {
            // 相对路径，转换为绝对路径
            storagePath = new File(storagePath).getAbsolutePath();
        } else if (!storagePath.contains(":") && !storagePath.startsWith("/")) {
            // 如果既不是绝对路径也不是以/开头的路径，视为相对路径
            storagePath = new File(storagePath).getAbsolutePath();
        }
        
        log.info("初始化本地存储策略 - 存储路径: {}, 访问路径: {}, 域名: {}", storagePath, accessPath, domain);
        
        return new StorageFactory.LocalStorageStrategy(this);
    }
    
    /**
     * 本地存储配置
     */
    @Data
    public static class Local {
        /**
         * 存储路径
         */
        private String storagePath = "upload";
        
        /**
         * 访问路径
         */
        private String accessPath = "/upload";
        
        /**
         * 访问域名，用于生成完整的URL
         */
        private String domain = "";
        
        /**
         * 获取存储路径，兼容老代码中的getPath()调用
         */
        public String getPath() {
            return storagePath;
        }
        
        /**
         * 获取访问URL，兼容老代码中的getUrl()调用
         */
        public String getUrl() {
            return accessPath;
        }
    }
    
    /**
     * 又拍云存储配置
     */
    @Data
    public static class UpYun {
        /**
         * 服务名称
         */
        private String bucketName;
        
        /**
         * 操作员名称
         */
        private String operatorName;
        
        /**
         * 操作员密码
         */
        private String operatorPwd;
        
        /**
         * 访问域名
         */
        private String domain;
    }
} 